const SparkMD5 = require('spark-md5')
const fs = require('fs')

const args = process.argv.slice(2);
if (!args.length) {
	console.error('[ERROR] 请提供文件夹路径')
	process.exit(-1)
}

let path = args[0];
let exist = fs.existsSync(path);
if (!exist) {
	console.error(`[ERROR] 文件夹${path}不存在`)
	process.exit(-1)
}

fs.readdir(path,  (err, files) => {
	files.forEach(file => {
		let oldFile = `${path}/${file}`;
		let buffer = fs.readFileSync(oldFile);
		let md5 = SparkMD5.ArrayBuffer.hash(buffer);

		let newFile = `${path}/${md5}`;
		fs.renameSync(oldFile, newFile);

		// 生成对应的数据库脚本文件
		let sql = `UPDATE system_file SET identifier = '${md5}' WHERE identifier = '${file}';\n`;
		fs.appendFileSync('./script.sql', sql);

		console.log(`${file} => ${md5}`);
	})

	console.log('[INFO] 执行完毕!')
})